local skynet = require "skynet"
local sprotoparser = require "sprotoparser"
local sprotoloader = require "sprotoloader"

local data = {}
local CMD = {} 

local function load(name) 
    local filename = string.format("proto/%s", name)
    local f = assert(io.open(filename), "Can't open " .. name)
    local t = f:read("a")
    f:close()
    return sprotoparser.parse(t)
end 

-- { "sproto1", "sproto2", ... }
function CMD.load(list) 
    for i, name in ipairs(list) do 
        local p = load(name) 
        skynet.error(string.format("load proto [%s] in slot %d", name, i))
        data[name] = i 
        sprotoloader.save(p, i)
    end 
end

function CMD.index(name)
    return data[name]
end 

skynet.start(function()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        local f = assert(CMD[cmd])
        skynet.ret(skynet.pack(f(...)))
    end)
end)